package middleware

import (
	"errors"
	"net/http"
	"ticket/internal/schemas"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		session := sessions.Default(ctx)
		userID := session.Get("user_id")
		if userID == nil {
			schemas.ResponseError(ctx, http.StatusUnauthorized, errors.New("未登录"))
			ctx.Abort()
			return
		}

		// 刷新session过期时间
		expires := viper.GetInt("jwt.expires")
		session.Options(sessions.Options{MaxAge: expires})
		session.Save()
		ctx.Set("user_id", userID)
		ctx.Next()
	}
}
